package com.syg.servlet04;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 *
 */
@WebServlet("/buyServlet")
public class _03_Disable_Cookie_BuyServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        _03_Disable_Cookie.Book book = _03_Disable_Cookie.DB.getAll().get(id);  //得到用户想买的书
        HttpSession session = req.getSession();
        List<_03_Disable_Cookie.Book> list = (List) session.getAttribute("list");  //得到用户用于保存所有书的容器
        if(list==null){
            list = new ArrayList<_03_Disable_Cookie.Book>();
            session.setAttribute("list", list);
        }
        list.add(book);
        //response. encodeRedirectURL(java.lang.String url)用于对sendRedirect方法后的url地址进行重写
        String url = resp.encodeRedirectURL(req.getContextPath()+"/listSrevlet");
        System.out.println(url);
        resp.sendRedirect(url);
    }
}
